<?php

/**
 * MVM_MALL 网上商店系统  购物车
 * ============================================================================
 * 版权所有 (C) 2007-2010 www.mvmmall.com，并保留所有权利。
 * 网站地址: http://www.mvmmall.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * $Author:  www.mvmmall.com  $
 * $Date: 2008-06-12 $
 * $Id: cart.php  www.mvmmall.com$
 * ---------------------------------------------
*/

require_once './include/common.inc.php';
require_once MVMMALL_ROOT.'./include/cart.class.php';
//判断营运状态
if ($mm_mall_form==1 && empty($m_check_id)){
	show_msg('login_please', "move");
}
switch ($action)
{
	case 'move_cart':
	{
		!$m_check_id && show_msg('login_please','logging.php?action=login');
		$ps_caid     = (int)$ps_caid;
		$rowset      = new cart();
		$rowset->move('cart',$ps_caid);
		unset($_SESSION['sum_cart']);
		move_page(dreferer());
		break;
	}
	case 'move_wish':
	{
		!$m_check_id && show_msg('wish_login_id','logging.php?action=login');
		$ps_caid     = (int)$ps_caid;
		$rowset      = new cart();
		$rowset->move('wish',$ps_caid);
		unset($_SESSION['sum_cart']);
		move_page(dreferer());
		break;
	}
	case 'change':
	{
		$rowset = new cart();
		$rowset->change($cart_list_num,$cart_uid);
		unset($_SESSION['sum_cart']);
		move_page(dreferer());
		break;
	}
	case 'delete':
	{
		$id     = (int)$id;
		$rowset = new cart();
		$rowset->delete($id);
		unset($_SESSION['sum_cart']);
		move_page(dreferer());
		break;
	}
	case 'alldelete':
	{
		$rowset = new cart();
		$rowset->delete(0);
		unset($_SESSION['sum_cart']);
		move_page(dreferer());
		break;
	}
	case 'list':
	{
		$rowset        = new cart();
		$cart_rt       = $rowset->cart_list();
		$cart_goods    = $cart_rt[0];
		$wish_goods    = $cart_rt[1];
		$total_price   = currency($rowset->total_price);
		$total_point   = $rowset->total_point;
		$navigation    = make_navigation($lang['cart_text'],GetBaseUrl('cart','list'));//导航
		$cart_buy_url  = GetBaseUrl('cart','buy');
		$mm_mall_title =  $lang[cart_text]; //标题
		require_once MVMMALL_ROOT . 'header.php';
		require_once template('cart');
		footer();
		break;
	}
	
	case 'buy':
	    {
	        $rowset      = new cart();
	        $rt          = $rowset->cart_list();
	        $_SESSION['cart']['goods'] = $cart_rt = $rt[0];
	        $_SESSION['cart']['goods_price'] = $rowset->total_price;
	        count($cart_rt)<=0 && show_msg ('cart_existence');
	        //包装方式
	        $wrapping = $cache->get_cache('pack');
	        //支付方式
	        $payment  = payment_list();
	        //调用收货地址列表
	        if ($m_check_id){
	            $member_address = array();
	            $add_rt         = array();
	            $result         = $db->query("SELECT * FROM `{$tablepre}address` WHERE member_id='$m_check_uid'");
	            while ($rt = $db->fetch_array($result)){
	                if ($rt['is_buy']== 1) {
	                    $rt['checked'] = 'checked="checked"';
	                    $add_rt = $rt;
	                }else {
	                    $rt['checked'] = '';
	                }
	                $member_address[] = $rt;
	            }
	        }
	        if (count($add_rt)>0) {
	            extract($add_rt,EXTR_OVERWRITE);
	            $disp = 'none';
	        }else {
	            $disp = 'block';
	        }
	        $goods_price = currency($rowset->total_price);
	        require_once MVMMALL_ROOT . 'header.php';
	        require_once template('cart_buy');
	        footer();
	        break;
	    }
	case 'pay':
	{
		empty($_SESSION['cart']['goods']) && exit($lang['cart_existence']);
		$ordersn           = date('Ymdhis');
		$total_price       = currency($_SESSION['cart']['goods_price']);
		$delivery_exes     = currency($_SESSION['cart']['ship_price']);
		$wrapping_price    = currency($_SESSION['cart']['pack_price']);
		$wrapping_method   = $_SESSION['cart']['pack_name'].' '.$wrapping_price;
		$delivery_method   = $_SESSION['cart']['ship_name'].' '.$delivery_exes;
		$buy_price         = floatval($_SESSION['cart']['goods_price']+$_SESSION['cart']['ship_price']+$_SESSION['cart']['pack_price']+$_SESSION['cart']['cess_price']);
		//生成支付代码
		$pay_id            = (int)$pay_id;
		$pay               = $db->get_one("SELECT * FROM {$tablepre}payment_table WHERE id='$pay_id'");
		require_once MVMMALL_ROOT.'./include/payment/'. $pay['class_name'].'.class.php';
		$rowst             = new  $pay['class_name'](unserialize($pay['cfg']));
		$code_form         = $rowst->pay_send($ordersn,$buy_price);
		$payment_method    =  $pay['name'];

		//团购处理
		$cart_type         = (int)$_SESSION['activity']['type'];
		$extension_id      = (int)$_SESSION['activity']['id'];
		if($cart_type==1 && $extension_id){
			//读团购活动数据
			$group        = $db->get_one("SELECT act_id,act_config FROM `{$tablepre}activity` WHERE act_id='$extension_id'");
			$act_config   = unserialize($group['act_config']);
			$act_config['buy_nums']++;//订购人数
			//写入团购扣款记录
			$price        =  $act_config['deposit'];//保证金
			$query        = "INSERT INTO `{$tablepre}money_table` SET
                             money_sess     = '$ordersn',
                             money_id       = '$m_check_id',
                             money_add      = '-$price',
                             money_category ='1',
                             money_reason   = '$lang[show_money]',
                             modify_ip      = '$m_user_ip',
                             register_date  = '$m_now_time'";
			$db->query($query);
			//更新会员存款内容信息
			$db->query("UPDATE {$tablepre}member_table SET  member_money = member_money -'$price' WHERE member_id = '$m_check_id'");

			if( $act_config['buy_nums']<$act_config['middle_nums'] ||  $act_config['buy_nums']<$act_config['end_nums'] ){
				$code_form = $lang['group_submit'];
				$cart_type = 3;
			}
			$act_config    = serialize($act_config);
			//更新购买人
			$db->query("UPDATE `{$tablepre}activity` SET act_config ='$act_config' WHERE act_id='$extension_id'");
		}
		//写入定单
		$buyer      = array();
		$consignee  = dhtmlchars($consignee);
		$email      = dhtmlchars($email);
		$phone      = dhtmlchars($phone);
		$mobile     = dhtmlchars($mobile);
		$zipcode    = dhtmlchars($zipcode);
		$address    = dhtmlchars($province.' '.$city.' '.$address);
		$buyer_main = dhtmlchars($buyer_main);
		if ($m_check_id) {
		    $user_rt           = $db->get_one("SELECT member_tel1,member_tel2,member_zip,province,city,member_address,member_id FROM `{$tablepre}member_table` WHERE member_id = '$m_check_id'");
			$buyer['username'] = $m_check_id;
			$buyer['name']     = $m_check_name;
			$buyer['address']  = $user_rt['province'].' '.$user_rt['city'].' '.$user_rt['$member_address'];
			$buyer['zip']      = $user_rt['member_zip'];
			$buyer['tel']      = $user_rt['member_tel1'];
			$buyer['telb']     = $user_rt['member_tel2'];
			$buyer['email']    = $m_check_email;
		}else {
		    $buyer['username'] = 'Guest';
			$buyer['name']     = $consignee;
			$buyer['address']  = $address;
			$buyer['zip']      = $zipcode;
			$buyer['tel']      = $phone;
			$buyer['telb']     = $mobile;
			$buyer['email']    = $email;
		}
		$query     = "INSERT INTO `{$tablepre}order_info` (`ordersn`, `username`, `buy_name`,`buy_address`, `buy_zipcode`, `buy_tel`, `buy_mobile`, `buy_email`, `addtime`, `status`, `consignee`, `address`, `zipcode`, `tel`, `mobile`, `email`, `cas_name`, `cas_exes`, `sh_id`, `sh_name`, `sh_exes`, `pay_id`, `pay_name`, `goods_amount`, `order_amount`, `remark`,`order_type`,`extension_id`,`invoice`)
                      VALUES ('$ordersn','$buyer[username]','$buyer[name]', '$buyer[address]', '$buyer[zip]', '$buyer[tel]', '$buyer[telb]', '$buyer[email]','$m_now_time', '1','$consignee','$address', '$zipcode', '$phone', '$mobile', '$email', '{$_SESSION['cart']['pack_name']}', '{$_SESSION['cart']['pack_price']}', '{$_SESSION['cart']['ship_id']}', '{$_SESSION['cart']['ship_name']}', '{$_SESSION['cart']['ship_price']}','$pay_id', 
                      '$pay[name]','{$_SESSION['cart']['goods_price']}', '$buy_price', '$buyer_main','$cart_type','$extension_id','$invoice');"; 
		$db->query($query);
		//写入定单商品数据
		$order_id = $db->insert_id();
		foreach ($_SESSION['cart']['goods'] as $val){
			$val['cart_subject'] = addslashes($val['cart_subject']);
			$val['att_value'] = addslashes($val['att_value']);
			$db->query("INSERT INTO `{$tablepre}order_goods` (`order_id`, `goods_id`, `goods_name`, `buy_number`, `mall_price`, `buy_price`, `goods_attr`,`register_date`)
                        VALUES ('$order_id','$val[cart_goods_id]', '$val[cart_subject]', '$val[cart_num]','$val[goods_sale_price]','$val[cart_price]','$val[goods_att]','$m_now_time')");
		}
		//写入支付记录表
		$db->query("INSERT INTO `{$tablepre}pay_log` (`order_sn`, `order_amount`,`order_type`, `status`) VALUES ('$ordersn','$buy_price', '0', '0')");
		//定单购买邮件发送
		if ($mm_mail_order==1){
			$mail_subject = $mm_mall_name.$lang[buy_payorder];
			include  template('email_order');
			$mail_content = clean_html('red');
			$mail_content =  str_replace('shopimg',MVMMALL_DIR .'/shopimg',$mail_content);
			$mail_content =  str_replace('images/pay',MVMMALL_DIR .'/images/pay',$mail_content);
			smtp_mail($email,$mail_subject,$mail_content);
		}
		//end

		//删除购物车的内容
		if($m_check_id) {
			if(isset($_SESSION['activity']['type'])){
				$cart_type = (int)$_SESSION['activity']['type'];
				$db->query("DELETE FROM `{$tablepre}cart_table` WHERE  cart_wish = '0' AND cart_id = '$m_check_id' AND cart_type='$cart_type'");
			}else {
				$db->query("DELETE FROM `{$tablepre}cart_table` WHERE  cart_wish = '0' AND cart_id = '$m_check_id' OR cart_sess = '$m_check_cart'");
			}
		}else{
			$db->query("DELETE FROM `{$tablepre}cart_table` WHERE cart_sess = '$m_check_cart' AND cart_wish = '0'");
		}
		unset($_SESSION['cart'],$_SESSION['mvm_sess_cart'],$_SESSION['activity'],$_SESSION['sum_cart']);
		$buy_price = currency($buy_price);
		include template('cart_end');
		clean_html();
		break;
	}
	case 'privilege':
	{
		$rowset  = new cart();
		$rowset->privilege($act_id);
		move_page(GetBaseUrl('cart','list'));
		break;
	}
	default:
	    {
	        $ps_goid = intval($ps_goid);
	        $ps_num  = intval($ps_num);
	        $rowset  = new cart();
	        $rowset->add($ps_goid,$ps_num,$ps_select,$att_value);
	        unset($_SESSION['sum_cart']);
	        if ($per=='ajax') {
	            $rowset->cart_list();
	            $arr = array('price'=>currency($rowset->total_price),
	            'nums' =>$rowset->total_count
	            );
	            require_once MVMMALL_ROOT.'./include/json.class.php';
	            $json = new Services_JSON;
	            echo $json->encode($arr);
	        }else {
	            move_page(GetBaseUrl('cart','list'));
	        }
	        break;
	    }
}